package com.mohunhun.controller;

import com.mohunhun.common.AppResult;
import com.mohunhun.common.ResultCode;
import com.mohunhun.config.AppConfig;
import com.mohunhun.exception.ApplicationException;
import com.mohunhun.model.Message;
import com.mohunhun.model.User;
import com.mohunhun.services.IMessageService;
import com.mohunhun.services.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Tag(name = "站内信接口")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @Operation(summary = "发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @Parameter(description = "接受者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @Parameter(description = "内容") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if (user.getId() == receiveUserId) {
            return AppResult.failed("不能给自已发送站内信");
        }

        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if (receiveUser.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }


        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);

        messageService.create(message);

        return AppResult.success();
    }

    @Operation(summary = "获取未读数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        return AppResult.success(messageService.selectUnreadCount(user.getId()));
    }

    @Operation(summary = "获取站内信列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        List<Message> messages = null;
        messages = messageService.selectByReceiveUserId(user.getId());
        if (messages == null) {
            messages = new ArrayList<>();
        }

        return AppResult.success(messages);
    }

    @Operation(summary = "更新站内信为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @Parameter(description = "站内信id") @RequestParam("id") @NonNull Long id) {

        Message message = messageService.selectById(id);

        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        if (message.getPostUserId() == user.getId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        messageService.updateStateById(message.getId(), (byte) 1);

        return AppResult.success();
    }

    @Operation(summary = "回复站帖子")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @Parameter(description = "接收者id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @Parameter(description = "回复内容") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }


        Message existsMessage = messageService.selectById(repliedId);

        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }

        if (existsMessage.getPostUserId() == user.getId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);
        message.setUpdateTime(new Date());

        messageService.reply(existsMessage.getId(), message);

        return AppResult.success();
    }
}
